'use client'

import React from 'react'
import { useRouter } from 'next/navigation'
import { importNote } from '@/compActions'

export default function SidebarImport() {
  const router = useRouter()

  const onChange = async (e) => {
    const fileInput = e.target;

    if (!fileInput.files || fileInput.files.length === 0) {
      console.warn("files list is empty");
      return;
    }

    const file = fileInput.files[0];

    const formData = new FormData();
    formData.append("file", file);

    try {
      const data = await importNote(formData);
      //在/app/action里：revalidatePath('/','layout')
      // 这里就不需要route.refresh()  因为当前是server Actions模式
      //清除路由缓存
      // servre action里：revalidatePath 或者revalidateTag cookie.set 或者cookie.delete
      // 非server action里  route.refresh()
      router.push(`/note/${data.uid}`)

    } catch (error) {
      console.error("something went wrong");
    }

    // 重置 file input
    e.target.type = "text";
    e.target.type = "file";
  };


  return (
    <div style={{ textAlign: "center" }}>
      <label
        htmlFor="file"
        style={{ cursor: 'pointer' }}>
        Import .md File (server Actions mode)
      </label>
      <input
        type="file"
        id="file"
        name="file"
        style={{ position: "absolute", clip: "rect(0 0 0 0)" }}
        onChange={onChange}
        accept=".md"
      />
    </div>
  )
}
